using System.Linq;
using UnityEngine;
using Weapons.Components.ComponentData;
using Weapons.Components.ComponentData.AttackData;

namespace Weapons.Components
{
    public class WeaponSprite : WeaponComponent<WeaponSpriteData, AttackSprites>
    {
        private SpriteRenderer baseSpriteRenderer;

        private Sprite[] currentPhaseSprites;


        private int currentWeaponSpriteIndex;
        private SpriteRenderer weaponSpriteRenderer;


        protected override void Start()
        {
            base.Start();
            baseSpriteRenderer = newWeapon.BaseGameObject.GetComponent<SpriteRenderer>();
            weaponSpriteRenderer = newWeapon.WeaponGameObject.GetComponent<SpriteRenderer>();

            //�̳�����ʱ���ڵ�����
            data = newWeapon.Data.GetData<WeaponSpriteData>();

            baseSpriteRenderer.RegisterSpriteChangeCallback(HandleBaseSpriteChange);

            eventHandler.OnEnterAttackPhase += HandleEnterAttackPhase;
        }


        protected override void OnDestroy()
        {
            base.OnDestroy();
            baseSpriteRenderer.UnregisterSpriteChangeCallback(HandleBaseSpriteChange);

            eventHandler.OnEnterAttackPhase -= HandleEnterAttackPhase;
        }

        //private WeaponSpriteData data;

        private void HandleEnterAttackPhase(AttackPhases phase)
        {
            currentWeaponSpriteIndex = 0;

            currentPhaseSprites = currentAttackData.PhaseSprites.FirstOrDefault(data => data.Phase == phase).Sprites;
        }

        protected override void HandleEnter()
        {
            base.HandleEnter();
            currentWeaponSpriteIndex = 0;
        }

        private void HandleBaseSpriteChange(SpriteRenderer sr)
        {
            if (!isAttackActive)
            {
                baseSpriteRenderer.sprite = null;
                weaponSpriteRenderer.sprite = null;
                return;
            }

            if (currentWeaponSpriteIndex >= currentPhaseSprites?.Length)
            {
                Debug.LogWarning($"{newWeapon.name} weapon sprites length mismatch");
                return;
            }

            //TODO�����ƣ����ڻ���Base�����л��������ε�ʱ����������Խ��Ĵ���
            weaponSpriteRenderer.sprite = currentPhaseSprites?[currentWeaponSpriteIndex];
            currentWeaponSpriteIndex++;
        }
    }
}